const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../../common/bee/bee')

router.post('/delete/role-menu', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { role_id, menu_id } = req.body
  if (!Bee.StringUtils.isNumber(role_id) || !Bee.StringUtils.isNumber(menu_id))
    return handleError(10003, '参数错误')

  const [deleteRoleMenuError, deleteRoleMenuSuccess] = await to(
    db.query('DELETE FROM role_menu WHERE role_id=? AND menu_id=?;', [
      role_id,
      menu_id,
    ])
  )
  if (
    deleteRoleMenuError ||
    !deleteRoleMenuSuccess ||
    deleteRoleMenuSuccess.affectedRows !== 1
  )
    return handleError(-1, deleteRoleMenuError)
  return resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
